<template>
	<div class="router-view bcl-white">
		<!-- 搜索框 -->
		<div class="search-header bcl-active p-10">
			<uni-search-box @onsubmit="onsubmit" @todata="todata"></uni-search-box>
		</div>

		<!-- 菜单栏 -->
		<div class="menu-list">
			<div class="border border-bottom pointer" @click="friend">
				<span class="icon icon-user"></span>
				<span>新的朋友</span>
			</div>
			<div class="border border-bottom pointer" @click="Group">
				<span class="icon icon-user"></span>
				<span>群聊</span>
			</div>
			<div class="border border-bottom pointer" @click="consultant">
				<span class="icon icon-user"></span>
				<span>顾问</span>
			</div>
		</div>

		<div style="border-top:10px solid #f8f8f8;">

			<div v-for="(item, index) in role_list" :key="item" @click.stop="onCompanyClick(item,index)">
				<div class="company">
					<u-icon color="#999999" size="36" name="home"></u-icon>{{item.name}}
				</div>

				<div v-if="item.isSelected" class="menu-list">
					<div class="border border-bottom pointer" v-for="(group, index1) in item.info" :key="index1" @click.stop="onGroupClick(item,index,group,index1)">
						<div class="company companys">
							<u-icon color="#999999" size="36" name="tags"></u-icon>{{group.name}}
						</div>
						<div v-if="group.isSelected" class="menu-list">
							<div class="border border-bottom pointer" @click.stop="friend" v-for="(itemsa, index2) in group.list" :key="index2">
								<span class="icon icon-user" style="padding:0 0 0 25rpx;"></span>
								<span>{{itemsa.name}}</span>

							</div>
						</div>
					</div>
				</div>
			</div>


		</div>

		<!-- 通讯录列表 -->
		<youxue-link-bar :index-list="indexs" @select="onSelect"></youxue-link-bar>
	</div>
</template>

<script>
	import {
		enterprise,
		userInfo
	} from "@/apis/user";
	import uniSearchBox from "@/components/searchBox";
	import youxueLinkBar from "@/components/linkBar";
	import {
		mapState,
		mapActions
	} from "vuex";
	import initTim from "@/utils/initTim";
	// #ifdef H5
	import TIM from 'tim-js-sdk';
	// #endif
	// #ifndef H5
	import TIM from 'tim-wx-sdk';
	// #endif
	export default {

		data() {
			return {
				indexs: [], //初始化为空
				todatas: '',
				avater: '',
				role_list: [],
				origin_indexs: [],
			};
		},
		created() {
			if (this.tim) this.listMessage();
			else this.initTim();

			this.enterprise()
		},

		methods: {
			// 数组关键字模糊查询
			searchKeywords(str, container) {
				var len = container.length;
				var newList = [];
				var reg = new RegExp(str);
				for (var i = 0; i < len; i++) {
					if (container[i].contents[0].nickname.match(reg)) {
						newList.push(container[i]);
					}
				}
				return newList;
			},
			onCompanyClick(company, index) {
				company.isSelected = !company.isSelected;
				this.$set(this.role_list, index, company);
			},
			onGroupClick(company, index, group, index1) {
				group.isSelected = !group.isSelected;
				this.$set(this.role_list[index].info, index1, group);
			},
			async enterprise() {
				let {
					code,
					data
				} = await enterprise();
				console.log("公司", data)
				if (code == 200) {
					data.role_list.forEach(item => {
						item.isSelected = false;
						item.info.forEach((group) => {
							group.isSelected = false;
						});
					});
					this.role_list = data.role_list
				}

			},
			onSelect(content) {
				console.log(content);
				this.toChatPage(content.to);
			},
			/*
			 * 初始化腾讯IM
			 */
			async initTim() {
				let tim = await initTim();
				this.SET_TIM(tim);
				this.listMessage();
			},
			/**
			 * 获取聊天列表
			 */
			async listMessage() {
				let {
					data
				} = await this.tim.getConversationList(2);
				console.log("获取聊天列表", data);
				let arr = [];
				for (let i = 0; i < data.conversationList.length; i++) {
					arr[i] = {
						name: "",
						contents: [{
							nickname: data.conversationList[i].userProfile.nick,
							to: data.conversationList[i].userProfile.userID,
							avatar: data.conversationList[i].userProfile.avatar ? data.conversationList[i].userProfile.avatar : this.avater,
						}],
					}
				}
				console.log("----->获取聊天列表arr", arr);
				this.origin_indexs = arr;
				this.indexs = arr;
			},

			/*
			 * 快速发起会话
			 */
			onsubmit(user) {
				//   let arr = [];
				//   arr.push(user);
				//   console.log("查询和修改好友",arr);
				//  let message =  this.tim.getUserProfile({
				//     userIDList: arr
				//   }).then(function(imResponse) {
				//     console.log(imResponse.data); // 存储用户资料的数组 - [Profile]
				//   }).catch(function(imError) {
				//     console.warn('getUserProfile error:', imError); // 获取其他用户资料失败的相关信息
				//   });
				//  console.log("查询和修改好友",message);

				let message = this.tim.createTextMessage({
					to: user,
					conversationType: TIM.TYPES.CONV_C2C,
					payload: {
						text: '您好'
					}
				});
				let promise = this.tim.sendMessage(message).then(function(imResponse) {
					// 发送成功
					console.log("发送成功", imResponse);
					uni.navigateTo({
						url: "/message/chat?toUserId=" + imResponse.data.message.to,
					});
				}).catch(function(imError) {
					// 发送失败
					alert(imError)
					console.warn('sendMessage error:', imError);
				});
			},
			todata(value) {
				this.todatas = value.toString();
				let result = this.searchKeywords(this.todatas, this.origin_indexs);
				this.indexs = result;
			},
			/*
			 * 添加朋友
			 */
			friend() {
				if (this.todata == '') {
					alert("请输入用户id");
				}
				let message = this.tim.createTextMessage({
					to: this.todatas,
					conversationType: TIM.TYPES.CONV_C2C,
					payload: {
						text: '您好'
					}
				});
				let promise = this.tim.sendMessage(message).then(function(imResponse) {
					// 发送成功
					console.log("发送成功", imResponse);
					uni.navigateTo({
						url: "/message/chat?toUserId=" + imResponse.data.message.to,
					});
				}).catch(function(imError) {
					// 发送失败
					alert(imError)
					console.warn('sendMessage error:', imError);
				});
			},
			/*
			 * 添加朋友
			 */
			Group() {
				if (this.todatas == '') {
					alert("请输入群id");
				}
				let promise = this.tim.joinGroup({
						groupID: this.todatas,
						type: TIM.TYPES.GRP_AVCHATROOM
					})
					.then(function(imResponse) {
						switch (imResponse.data.status) {
							case TIM.TYPES.JOIN_STATUS_WAIT_APPROVAL:
								alert(等待管理员同意);
								break; // 等待管理员同意
							case TIM.TYPES.JOIN_STATUS_SUCCESS: // 加群成功
								console.log(imResponse.data.group); // 加入的群组资料
								alert(加群成功);
								break;
							case TIM.TYPES.JOIN_STATUS_ALREADY_IN_GROUP: // 已经在群中
								alert(已经在群中);
								break;
							default:
								break;
						}
					}).catch(function(imError) {
						alert(imError);
						console.warn('joinGroup error:', imError); // 申请加群失败的相关信息
					});
			},
			/*
			 * 顾问
			 */
			async consultant() {
				let {
					code,
					data
				} = await userInfo();
				if(code === 200){
					this.todatas = data.guwen_id;
					console.log(this.todatas);
					if (this.todatas == null || this.todatas === '') {
						this.$toast('您还没有顾问');
						return;
					}
					let message = this.tim.createTextMessage({
						to: '' + this.todatas,
						conversationType: TIM.TYPES.CONV_C2C,
						payload: {
							text: '您好'
						}
					});
					let promise = this.tim.sendMessage(message).then(function(imResponse) {
						// 发送成功
						console.log("发送成功", imResponse);
						uni.navigateTo({
							url: "/message/chat?toUserId=" + imResponse.data.message.to,
						});
					}).catch(function(imError) {
						// 发送失败
						alert(imError)
						console.warn('sendMessage error:', imError);
					});
				}
				
				
			},

			...mapActions(["SET_TIM"]),
		},
		computed: {
			...mapState(["userInfo", "tim"]),
		},

		components: {
			uniSearchBox,
			youxueLinkBar,
		},
	};
</script>

<style lang="scss" scoped>
	.router-view {
		.menu-list {
			&>div {
				padding: 25rpx 20rpx;
			}
		}
	}

	.company {
		padding: 25rpx 20rpx;
		border-bottom: 1px solid #eeeeee;

		.u-icon {
			padding: 0 10rpx 0 0;
		}
	}

	.companys {
		padding: 5rpx 20rpx 25rpx 20rpx;
	}
</style>
